package SocketDemo.TCP;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author:周鹏
 * @date: 2020/11/9 10:28
 * @description:
 */
public class NetServer {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        InputStream is = null;
        Socket socket = null;
        ByteArrayOutputStream baos = null;
            try {
                //设置服务器端口号
                serverSocket = new ServerSocket(9090);
                //新建立socket与客户端链接
                socket = serverSocket.accept();
                //输出io流读取信息
                is = socket.getInputStream();
                //借助数组管道流输出信息（接受任意类型数据）
//                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
//                while ((len = is.read(buffer)) != -1) {
//                    baos.write(buffer, 0, len);
//
//                }
//                System.out.println(baos.toString());

                //文件输出服务端
                FileOutputStream fn=new FileOutputStream(new File("demo.txt"));
                while((len=is.read(buffer))!=-1){
                    fn.write(buffer,0,len);
                }
                //等待客户端输出完毕才执行
                OutputStream os=socket.getOutputStream();
                os.write("服务器接收完毕".getBytes());
             //顺序关闭连接和流
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

                if (baos != null) {
                    try {
                        baos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


                if (serverSocket != null) {
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


            }
        }
    }

